package com.lynn.blog.controller;

import com.lynn.blog.common.ApiResponse;
import com.lynn.blog.common.TokenHolder;
import com.lynn.blog.dto.RegisterDTO;
import com.lynn.blog.entity.User;
import com.lynn.blog.service.UserService;
import com.lynn.blog.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Author: Lynn
 * Date: 2024/07/15 下午5:16
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public ApiResponse<String> register(@Validated @RequestBody RegisterDTO user) {
        String token = userService.register(user);
        return StringUtils.hasText(token) ?
                ApiResponse.success("注册成功", token) : ApiResponse.error(500, "注册失败");
    }

    @PostMapping("/login")
    public ApiResponse<String> login(@RequestParam String username,
                                     @RequestParam String password) {
        String token = userService.login(username, password);
        return StringUtils.hasText(token)
                ? ApiResponse.success("登录成功", token) : ApiResponse.error(500, "登录失败");
    }

    @GetMapping("/me")
    public ApiResponse<String> me() {
        return ApiResponse.success(JwtUtil.getUsernameFromToken(TokenHolder.getToken()));
    }
}
